<script setup>
import { forEach } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks.js';
import { useResetForm } from '@/hooks/tool.js';
import { useWatch } from '@/hooks/useWatch.js';
import { getAvailableList, getReportTree, getProjectInfo } from '@/api/index.js';
import EnterpriseTree from '@/components/EnterpriseInfo/EnterpriseTree.vue';
import ConfirmModal from '@/components/ConfirmModal.vue';
const props = defineProps({
  enterpriseCode: { type: String, default: '' },
  cancel: { type: Boolean, delete: null },
  mpbiDisabled: { type: Boolean, default: false },
  open: { type: Boolean, default: false },
  mpbiReportCode: { type: String, default: '' },
  openTitle: { type: String, default: () => '' },
});
const { enterpriseCode, cancel, mpbiDisabled, open, mpbiReportCode, openTitle } = toRefs(props);
const emit = defineEmits(['selectReport']);
const reportTable = ref(null);
const Forms = ref(null);
const queryParams = ref({
  projectName: '',
  reportCode: '',
});
const availableLists = ref([]);
const [, , availableRun] = useRequest(getAvailableList, {
  defaultParams: [{ enterpriseCode: props.enterpriseCode }],
  manual: true,
  onSuccess: data => {
    availableLists.value = data.rows;
  },
});
const [kxxbgfcData, , kxxbgfcRun] = useRequest(getReportTree, {
  defaultParams: [],
  manual: true,
});
const [editAvailableLists, , editAvailableRun] = useRequest(getAvailableList, {
  defaultParams: [],
  manual: true,
  // onSuccess: data => {
  //   let obj = handleQuery({ projectCode: mpbiReportCode.value });
  //   projectInfoRun(obj);
  // },
});
const [projectInfoLists, projectInfoLoading, projectInfoRun] = useRequest(getProjectInfo, {
  defaultParams: [{ projectCode: props.mpbiReportCode }],
  manual: true,
  onSuccess: async data => {
    let n = data.data;
    queryParams.value.projectName = n?.projectName ?? '';
    queryParams.value.reportCode = n?.reportCode ?? '';
    emit('selectReport', queryParams.value);
    let arr = [];
    let obj = {
      reportFileName: n.reportName,
      reportCode: n.reportCode,
      createTime: n.reportLastTime,
      // disabled: true,
    };
    arr.push(obj);
    if (openTitle.value === '详情') {
      availableLists.value = arr;
      reportTable.value.clearSelection();
      await nextTick(() => {
        reportTable.value.toggleRowSelection(obj, true);
      });
      kxxbgfcRun({ reportCode: availableLists.value[0].reportCode });
    } else if (openTitle.value === '编辑') {
      let obj2 = handleQuery({ enterpriseCode: props.enterpriseCode, excludeReportCode: n.reportCode });
      editAvailableRun(obj2);
      availableLists.value = arr;
      queryParams.value.reportCode = obj.reportCode;
      reportTable.value.clearSelection();
      await nextTick(() => {
        reportTable.value.toggleRowSelection(obj, true);
      });
      kxxbgfcRun({ reportCode: n.reportCode });
    }
  },
});
const handleQuery = params => {
  let formdata = new FormData(); //new出来的对象
  Object.keys(params).forEach(key => {
    formdata.append(key, params[key]);
  });
  return formdata;
};
const select = (selection, row) => {
  if (selection.length > 1) {
    const del_row = selection.shift();
    reportTable.value.toggleRowSelection(del_row, false);
    kxxbgfcRun({ reportCode: selection[0].reportCode });
    queryParams.value.reportCode = selection[0].reportCode;
    Forms.value.validateField('reportCode');
  } else if (selection.length === 1) {
    kxxbgfcRun({ reportCode: selection[0].reportCode });
    queryParams.value.reportCode = selection[0].reportCode;
    Forms.value.validateField('reportCode');
  } else {
    queryParams.value.reportCode = '';
    kxxbgfcRun({ reportCode: '' });
  }
  emit('selectReport', queryParams.value);
};
const handleSelectionChange = val => {
  // reportRun({ reportCode: val[0].reportCode });
};
const changeProjectName = val => {
  emit('selectReport', queryParams.value);
};
const isRowDisabled = row => {
  if (openTitle.value === '详情' || mpbiDisabled.value) {
    if (row.disabled) {
      return false;
    }
  } else {
    return true;
  }
};
useWatch(
  cancel,
  n => {
    if (n === true) {
      useResetForm(Forms);
      queryParams.value = {
        projectName: '',
        reportCode: '',
      };
      kxxbgfcData.value = [];
    } else if (n === false) {
      if (openTitle.value === '新增') {
        let obj2 = handleQuery({ enterpriseCode: props.enterpriseCode });
        availableRun(obj2);
      } else {
        let obj = handleQuery({ projectCode: mpbiReportCode.value });
        projectInfoRun(obj);
      }
    }
  },
  { deep: true, immediate: true },
);
useWatch(
  mpbiDisabled,
  n => {
    if (n) {
    }
  },
  { deep: true, immediate: true },
);
useWatch(editAvailableLists, n => {
  forEach(n.rows, el => {
    availableLists.value.push(el);
  });
});
</script>
<template>
  <div v-loading="projectInfoLoading">
    <el-form
      :model="queryParams"
      ref="Forms"
      size="small"
      label-width="130px"
      class="uploadForm u-mt20"
      :disabled="mpbiDisabled"
    >
      <el-form-item
        label="托管项目名称："
        prop="projectName"
        :rules="{ required: true, message: '请输入托管项目名称', trigger: 'blur' }"
      >
        <el-input
          v-filter-input
          style="width: 400px"
          v-model.trim="queryParams.projectName"
          placeholder="请输入托管项目名称"
          clearable
          size="small"
          @change="changeProjectName"
        />
      </el-form-item>
      <el-form-item
        label="关联可行性报告"
        prop="reportCode"
        :rules="{ required: true, message: '请选择', trigger: 'change' }"
      ></el-form-item>
    </el-form>
    <el-table
      ref="reportTable"
      :data="availableLists ?? []"
      @selection-change="handleSelectionChange"
      @select="select"
      :row-disabled="true"
    >
      <el-table-column type="selection" width="50px" :selectable="isRowDisabled" />
      <el-table-column prop="reportFileName" label="报告文件"></el-table-column>
      <el-table-column prop="createTime" label="上传日期"></el-table-column>
    </el-table>
    <EnterpriseTree :data="kxxbgfcData" />
    <ConfirmModal :msg="'所选报告关联区域与其他项目重复不可保存'" />
  </div>
</template>
<style lang="scss" scoped>
::v-deep .el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
